// #include <PcapLiveDeviceList.h>
#include <PfRingDeviceList.h>
#include <Packet.h>
#include <iostream>
#include "headers/flowUniAttr.h"
#include <IPv4Layer.h>
#include <PcapFileDevice.h>
#include <chrono>
#include <signal.h>
#include <filesystem>
#include <vector>

namespace fs = std::filesystem;
using namespace std;

// 假设你有这样一个函数来处理PCAP文件并输出CSV
void processPcapFileToCsv(const std::string& pcapPath, const std::string& tag,std::ofstream& outputFile) {

    // 打开pcap文件，获得reader
	pcpp::PcapFileReaderDevice reader(pcapPath);
	if (!reader.open())
	{
		std::cerr << "Error opening the pcap file" << std::endl;
		return;
	}

    // 判断能否读包
	pcpp::RawPacket rawPacket;
	if (!reader.getNextPacket(rawPacket))
	{
		std::cerr << "Couldn't read the first packet in the file" << std::endl;
		return;
	}


	operator_UniAttr* packetHandler = new operator_UniAttr();

	long long pac_count=0;
	while(reader.getNextPacket(rawPacket))
	{
		// 解析数据包
		pcpp::Packet parsedPacket(&rawPacket);

		// verify the packet is IPv4
		if (parsedPacket.isPacketOfType(pcpp::IPv4))
		{	
			// 准备搜集算子
			packetHandler->handle_packet(&parsedPacket);
			pac_count++;
		}
	}
	
	std::cout<<"Pcap parsing finished. Totol packet counts:"<<pac_count<<std::endl;
	reader.close();

	packetHandler->to_csv(outputFile,tag); //write to files
	delete packetHandler;
    }

int main(int argc, char *argv[]) {
    if (argc != 3) {
        std::cerr << "Usage: pcap2csv <input_txt_file> <output_csv_path>" << std::endl;
		std::cerr<<"Example: ./bin/pcap2csv /home/njust/program/pcapplusplus-23.09-ubuntu-20.04-gcc-9.4.0-x86_64/backend-demo/data/traffic/数据集1/TrafficSets.txt /home/njust/program/pcapplusplus-23.09-ubuntu-20.04-gcc-9.4.0-x86_64/backend-demo/data/traffic/数据集1/FlowAttr.csv"<<std::endl;
        return 1;
    }

    std::string txtFilePath = argv[1];
    std::string outputCsvPath = argv[2];

    std::ifstream inputFile(txtFilePath);
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open input file: " << txtFilePath << std::endl;
        return 1;
    }

    std::string line;
	// CSV文件操作
	std::ofstream outputFile(outputCsvPath);
	if (!outputFile.is_open()) {
		std::cerr << "Failed to open output file." << std::endl;
		return -1;
	}
	
    while (std::getline(inputFile, line)) {  //逐行遍历path和tag
        std::istringstream iss(line);
        std::string pcapPath, tag;
        if (!(iss >> pcapPath >> tag)) {
            std::cerr << "Invalid line format: " << line << std::endl;
            continue;
        }
        processPcapFileToCsv(pcapPath, tag, outputFile);
    }
	// 关闭文件
	outputFile.close();
    inputFile.close();
	return 0;
}